from django.core.paginator import PageNotAnInteger, Paginator
from django.conf import settings
from django.template import Template, Context
from django.http import JsonResponse

from rest_framework.views import APIView


from main.utils.util_db import MySqlHandler, get_query_connection
from main.utils.util_response import DetailResponse, ErrorResponse
from main.utils.util_db import DbException

import main.migrates.sql as table_sql

class DbQueryView(APIView):
    def post(self, request):
        sql=request.data.get('sql')
        db_type=request.data.get('db_type')
        db_name=request.data.get('db_name')
        handler = MySqlHandler(settings.DB_INSTANCE)
        items = [item for item in handler.query( table_sql.SQL_DB_INFO) if item['db_type']== db_type and item['db_name']==db_name]
        if len(items)==0:
            return ErrorResponse(msg = '未指定数据库或数据库不存在', code=20001)
        db_info = items[0]
        data = []
        try:
            with get_query_connection(db_info).connection as conn:
                cursor = conn.cursor()
                cursor.execute(sql)
                data = cursor.fetchmany(100)
            return DetailResponse(data=data)
        except DbException as e:
            return ErrorResponse(msg=e.msg, code = 20001)


# def sql_template_convert(request):
#     if request.method == 'POST':
#         sql = request.body
#     data = json.loads(sql)
#     sql = data.get('sql')
#     print(sql)
#     params = data.get('params')
#     tempalte = Template(sql)
#     context = Context(params)
#     result = tempalte.render(context)
#     return JsonResponse({ "code":20000,"data":{"result": result}})